<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
	  
	
	  
      <!-- <el-form-item label="所属员工" prop="belUserId">
        <el-input
          v-model="queryParams.belUserId"
          placeholder="请输入所属员工"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属门店" prop="belDeptId">
        <el-input
          v-model="queryParams.belDeptId"
          placeholder="请输入所属门店"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
	  <el-form-item label="订单类型" prop="type">
	    <el-select v-model="queryParams.type" placeholder="请选择订单类型" clearable>
	      <el-option
	        v-for="dict in bus_order_type"
	        :key="dict.value"
	        :label="dict.label"
	        :value="dict.value"
	      />
	    </el-select>
	  </el-form-item>
      <el-form-item label="支付方式" prop="payWay">
        <el-select v-model="queryParams.payWay" placeholder="请选择支付方式" clearable>
          <el-option
            v-for="dict in bus_pay_way"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
	  <el-form-item label="状态" prop="status">
	    <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
	      <el-option
	        v-for="dict in bus_sale_status"
	        :key="dict.value"
	        :label="dict.label"
	        :value="dict.value"
	      />
	    </el-select>
	  </el-form-item>
      <el-form-item label="收银员" prop="cashier">
        <el-input
          v-model="queryParams.cashier"
          placeholder="请输入收银员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="saleOrderList" style="height: calc(100vh - 290px);" @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed="left" width="55" align="center" />
      <el-table-column label="订单编号" fixed="left" align="center" prop="orderNo" width="200">
		  <template #default="scope">
			  <el-text type="primary" style="cursor: pointer;" @click="handleOpenGoodList(scope.row)">{{scope.row.orderNo}}</el-text>
		  </template>
	  </el-table-column>
	  <el-table-column label="订单类型" fixed="left" align="center" prop="type" width="90">
	  		<template #default="scope">
				<dict-tag :options="bus_order_type" :value="scope.row.type"/>
	  		</template>
	  </el-table-column>
      <el-table-column label="销售" align="center" prop="belUserId" />
     <!-- <el-table-column label="所属门店" align="center" prop="belDeptId" /> -->
      <el-table-column label="订单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打印时间" align="center" prop="printTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.printTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总数" align="center" prop="total" />
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="现价" align="center" prop="currentPrice" />
      <el-table-column label="实收" align="center" prop="receiptsPrice" />
      <el-table-column label="找零" align="center" prop="returnPrice" />
      <el-table-column label="折扣" align="center" prop="discount" />
      <el-table-column label="支付方式" align="center" prop="payWay">
        <template #default="scope">
          <dict-tag v-if="scope.row.payWay!='99'" :options="bus_pay_way" :value="scope.row.payWay"/>
		  <el-text type="primary" v-if="scope.row.payWay=='99'">储值卡</el-text>
        </template>
      </el-table-column>
      <!-- <el-table-column label="支付id" align="center" prop="payId" /> -->
      <el-table-column label="收银员" align="center" prop="cashier" />
	  <el-table-column label="状态" align="center" prop="status" fixed="right">
	    <template #default="scope">
	      <dict-tag :options="bus_sale_status" :value="scope.row.status"/>
	    </template>
	  </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
		  <div v-if="scope.row.type=='goods'">
			  <el-button v-if="scope.row.status=='1'" link type="primary" icon="MessageBox" @click="handlePrint(scope.row)">补打小票</el-button>
			  <el-button v-if="scope.row.status=='1'" link type="primary" icon="Delete" @click="handleRevoke(scope.row)" v-hasPermi="['crm:saleOrder:remove']">撤单</el-button>
		  </div>
		   <div v-else>
			   <el-text type="info">次卡测单请前往->次卡管理</el-text>
		   </div>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售单据对话框 -->
    <el-dialog :title="title" v-model="open" width="70%" append-to-body destroy-on-close>
		<saleGoods v-if="orderType=='goods'" :orderId = "orderId" />
		<countSale v-if="orderType=='card'" :orderId = "orderId"/>
    </el-dialog>
  </div>
</template>

<script setup name="SaleOrder">
import { ElMessageBox } from 'element-plus'
import { listSaleOrder, getSaleOrder, delSaleOrder, addSaleOrder, updateSaleOrder } from "@/api/crm/saleOrder";

import { addSaleRevoke } from "@/api/crm/saleRevoke";
import saleGoods from '../saleGoods/index.vue'

import countSale from '../countSale/info.vue'


import { print } from "@/api/crm/localOrder";

const { proxy } = getCurrentInstance();
const { bus_pay_way,bus_sale_status,bus_order_type } = proxy.useDict('bus_pay_way','bus_sale_status','bus_order_type');

const saleOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const orderType = ref(null);

const orderId = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
	type:null,
    belUserId: null,
    belDeptId: null,
    orderTime: null,
    printTime: null,
    total: null,
    originalPrice: null,
    currentPrice: null,
    receiptsPrice: null,
    returnPrice: null,
    discount: null,
    payWay: null,
    payId: null,
    cashier: null,
	status:'1',
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询销售单据列表 */
function getList() {
  loading.value = true;
  listSaleOrder(queryParams.value).then(response => {
    saleOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    belUserId: null,
    belDeptId: null,
    orderTime: null,
    printTime: null,
    total: null,
    originalPrice: null,
    currentPrice: null,
    receiptsPrice: null,
    returnPrice: null,
    discount: null,
    payWay: null,
    payId: null,
    cashier: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("saleOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售单据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSaleOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改销售单据";
  });
}

function handleRevoke(row){
	proxy.$modal.confirm('您确定要撤销该笔订单，并恢复该库存吗?').then(function() {
	  return  ElMessageBox.prompt('请输入撤销原因', '输入提示', {
				confirmButtonText: '确定撤销',
				cancelButtonText: '取消',
				inputPattern:
				  /[\u4e00-\u9fa5]{2,}/,
				inputErrorMessage: '请输入两个中文以上撤销原因',
			  });
	}).then((v) => {
		addSaleRevoke({orderId:row.id,revokeReason:v.value}).then(rsp=>{
			proxy.$modal.msgSuccess("撤销成功");
			getList();
		});
		
	}).catch(() => {});
}

function handleOpenGoodList(row){
	orderId.value = row.id;
	if('goods'==row.type){
		//console.log(orderId.id)
		title.value='订单商品信息'
		open.value = true;
		orderType.value ='goods';
	}else  if('card'==row.type){
		
		title.value='卡次信息'
		open.value = true;
		orderType.value = 'card'
	}else{
		orderType.value =null;
	}
	
	

}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["saleOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSaleOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSaleOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售单据编号为"' + _ids + '"的数据项？').then(function() {
    return delSaleOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('crm/saleOrder/export', {
    ...queryParams.value
  }, `saleOrder_${new Date().getTime()}.xlsx`)
}


//补打小票
function handlePrint(row){
	print(row.id).then(rsp=>{
		if(rsp.code!=200){
			proxy.$modal.notifyError(rsp.msg||'打印机处理异常，请检查打印机是否已开启并状态正常');
		}else{
			proxy.$modal.notifySuccess('发送打印机成功！')
			getList();
		}
	})
}

getList();
</script>
